#include "SemanticNodeUsing.h"

#include "main2.h"


SemanticNodeUsing::SemanticNodeUsing(SyntaxTreeNode & syntaxNode, SemanticNodeUsing* parentUsing, SemanticNode *parent) :
	SemanticNode(parent) {

	this->parentUsing = parentUsing;
	for (int i = 0; i < syntaxNode.Nodes->GetCount(); i++) {
		std::string us = flattenNamePeriodAdd(*syntaxNode.Nodes->GetData(i)->Nodes->GetData(1));
		if (syntaxNode.Nodes->GetData(i)->Production == Gr_UsingDirective__using_Name_spSemiCol) {
			usingWithoutAlias.push_back(us);
		} else if (syntaxNode.Nodes->GetData(i)->Production == Gr_UsingDirective__using_Name_as_NAME_spSemiCol) {
			LexicUnit lu = CompilerData->Units->GetLexicUnit(syntaxNode.Nodes->GetData(i)->Nodes->GetData(3)->LexUnitID);
			std::string alias = CompilerData->Units->GetLexicUnitString(&lu);
			// mozda treba pogledat da vec ne postoji isti alias - sta onda?
			usingWithAlias[alias] = us;
		}
	}

}

SemanticNodeUsing::~SemanticNodeUsing() {
}

SemanticNodeUsing* SemanticNodeUsing::getUsingNode() {
	// ako postujemo naziv, pripadni using blok ovog noda je on sam
	// mislim da bi se ovo s druge strane moglo iskoristit za vracanje njegovog parenta - posto je to skakljiva tema za sad stavljam this
	return this;
}

bool SemanticNodeUsing::containsName(std::string name) {
	for (std::vector<std::string>::iterator i = usingWithoutAlias.begin(); i != usingWithoutAlias.end(); ++i)
		if (*i == name)
			return true;
	for (std::map<std::string, std::string>::iterator i = usingWithAlias.begin(); i != usingWithAlias.end(); ++i)
		if (i->first == name)
			return true;
	if (parentUsing != NULL)
		return parentUsing->containsName(name);
	return false;
}

std::string SemanticNodeUsing::toDebugString(int tab) {
	std::ostringstream ss;
	for (std::vector<std::string>::iterator i = usingWithoutAlias.begin(); i != usingWithoutAlias.end(); ++i) {
		for (int j = 0; j < tab; j++)
			ss << DEBUG_STRING_RAZMAK;
		ss << "using " << *i << std::endl;
	}
	for (std::map<std::string, std::string>::iterator i = usingWithAlias.begin(); i != usingWithAlias.end(); ++i) {
		for (int j = 0; j < tab; j++)
			ss << DEBUG_STRING_RAZMAK;
		ss << "using " << i->second << " as " << i->first << std::endl;
	}
	if (parentUsing != NULL)
		ss << parentUsing->toDebugString(tab);
	return ss.str();
}

